package softtech.app.secretcaller;

import java.util.ArrayList;

import android.content.Context;
import android.os.AsyncTask;

public class ControlsSyncSecretContact extends AsyncTask<Void, Void, Void>{

	Context mContext;
	DatabaseHandler db;
	
	int user_id;
	
	ControlsSyncSecretContact(Context context){
		super();
		mContext = context;
		db = new DatabaseHandler(context);
	}
	
	@Override
	protected Void doInBackground(Void... params) {

		return null;
	}

	@Override
	protected void onPreExecute() {
		DatabaseUser user = getUserInfo();
		if(user!=null && !user.equals(null)){
			ControlsGetAllContactsFromServer taskGetAll = new ControlsGetAllContactsFromServer(mContext , user );
			taskGetAll.execute(null,null,null);
		}
		
		super.onPreExecute();
	}

	@Override
	protected void onPostExecute(Void result) {
		super.onPostExecute(result);
		if(user_id < 0 ){
			return;
		}
		ArrayList<DatabaseContact> listContacts = db.getAllContacts(user_id);
		
		if(listContacts.size()>0){
			for(int i = 0 ; i < listContacts.size(); i ++ ){
				if(listContacts.get(i).getIsSync() <= 0 ){
					ControlUploadToServer taskUpload = new ControlUploadToServer(mContext , listContacts.get(i) );
					taskUpload.execute(null,null,null);
				}				
			}
		}
		try{
			if (db != null) {
				db.close();
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * Get User Info
	 * @return
	 */
	DatabaseUser getUserInfo(){
		user_id = checkLogin(mContext);
		if(user_id<0){
			return null;
		}
		return db.getUser(user_id);
	}
	
	/**
	 * Check Login - (-1) : if not login. - id_login : if logged in.
	 */
	int checkLogin(Context context) {
		int id = -1;
		ToolsSaveFile tsf = new ToolsSaveFile();

		String id_loggedin = tsf.LoadContentFile(context,
				ConstantsFileName.FILE_ID_LOG_IN);

		if (id_loggedin == null || id_loggedin.equals("")
				|| id_loggedin.length() == 0) {

			id = -1;
		} else {
			try {
				id = Integer.parseInt(id_loggedin);

			} catch (Exception e) {
				id = -1;
				e.printStackTrace();
			}
		}

		return id;
	}
	
}
